package com.erp.app.report.genericInquiry;

import java.io.ByteArrayOutputStream;
import java.util.Collection;
import java.util.Iterator;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionServlet;

import com.erp.app.common.ProjectConstants;
import com.erp.app.report.genericInquiry.inquirySp.beans.vo.InquirySpVO;
import com.erp.framework.SimpleConstants;
import com.erp.framework.util.CommonUtil;
import com.erp.framework.util.logger.Logger;
import com.erp.framework.util.user.User;

public class GenericPdfGenerator extends GenericFileGenerator {
    public GenericPdfGenerator(GenericInquirySearchForm form) {
		super(form);
		this.isUseDynamicClass = true;
	}

	protected void preprocess(HttpServletRequest request, HttpServletResponse response,
            ActionServlet servlet, ActionErrors errors) {
    }

    protected ByteArrayOutputStream genContent(
            ActionMapping mapping,
            HttpServletRequest request, HttpServletResponse response,
            ActionServlet servlet, ActionErrors errors) throws Exception {
    	HttpSession session = request.getSession(false);
    	User editingUser = (User) session.getAttribute(SimpleConstants.SESSION_USER);
    	String inquiryType = form.getInquiryType();

        ServletContext sc = servlet.getServletContext();

        Collection srcs = null;
        
        //Collection spList = form.getGenericInquiryMasterVO().getChilds(InquirySpVO.class, editingUser.getUserId());
        Collection spList = form.getGenericInquiryMasterVO().getChilds(InquirySpVO.class);
        
        String pdfFlag = "";
        
        for(Iterator spIt = spList.iterator(); spIt.hasNext();) {
            InquirySpVO spVo = (InquirySpVO)spIt.next();
            pdfFlag = spVo.getPdfFlag() == null ? ProjectConstants.GENERIC_NO : spVo.getPdfFlag();
        }
        
        Logger.info(this, "The PDF Flag is : " + pdfFlag);

       	ByteArrayOutputStream baos = createReportByteArray(GenericInquiryConstants.JAVA_TYPE_PDF, ProjectConstants.GENERIC_YES.equals(pdfFlag), mapping, request, response, servlet, errors);
       	
       	if (baos == null)
       		throw new NullPointerException("Unable to create report from java class. (java class not found.)");
       	
        String filename = CommonUtil.toValidFileName(form.getFilename()) + ".pdf";
        
        response.setContentType("application/pdf");
        response.setHeader("Content-Disposition", "attachment;filename=\"" + filename + "\"");
        response.setHeader("Cache-control", "private");
        response.setHeader("Pragma", null);
       	
       	return baos;
    }
}
